﻿using System;
using System.Data;
using System.Text.RegularExpressions;
using System.Web;
using Jayden.Dll.Web;
using Jayden.Dll.Web.Enums;
using Jayden.Dll.Web.HtmlControls;
using Jayden.Dll.Web.HtmlControls.Generics;

namespace Jayden.Site.BvD.Dll
{
	public class ProductSearchDiv : Div
	{
		private Input m_SearcProduct;
		private Input m_SeqNo;
		private Select m_ProductType;
		private Table m_Table;

		public BvDPageHtml Page { get { return Root as BvDPageHtml; } }

		public override void Load(System.Xml.XmlNode node, Jayden.Dll.Web.HtmlControlLoader loader)
		{
			base.Load(node, loader);

			m_Table = GetElementByServerId<Table>("productTable", true);
			m_SeqNo = GetElementByServerId<Input>("seqNo", true, true);
			m_SearcProduct = GetElementByServerId<Input>("searchProduct", true);
			m_ProductType = GetElementByServerId<Select>("productType", true);

		}

		public override void ProcessCssRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			context.Css.NewElement("#" + m_Table.Id + " td").AddProperty("border", "solid 1px #000").AddProperty("padding", "2px");

			base.ProcessCssRequest(context);
		}

		public override void ProcessJsRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			context.Js[typeof(BvDPageHtml).FullName].AppendOnInit(@"
	var $table = $('#" + m_Table.Id + @"');
	var $searchProduct = $('#" + m_SearcProduct.Id + @"');
	var $productType = $('#" + m_ProductType.Id + @"');
	var seqNo = 0;
	var lastSeqNo = -1;
	var success = function(data) {
		if(typeof(data.products) !== 'undefined' && data.seqNo !== undefined && data.seqNo > lastSeqNo) {
			$table.html(data.products);
			lastSeqNo = data.seqNo;
		}
	};
	var refreshProducts = function() {
		$.ajax({
			data: {
				format:'json',
				refreshProducts:true,
				productType:$productType.val(),
				searchProduct:$searchProduct.val(),
				seqNo: seqNo
			},
			success:success,
			type:'post',
			dataType:'json'
		});
		seqNo ++;
	};
	$productType.change(refreshProducts);
	$searchProduct.keyup(refreshProducts);
	$table.on('mouseenter', 'tr', function() {
		$(this).addClass('mouseOver');
	}).on('mouseleave', 'tr', function() {
		$(this).removeClass('mouseOver');
	})
");

			base.ProcessJsRequest(context);
		}

		private Regex m_Regex = null;
		public override void ProcessJsonRequest(HttpHandlerContext context)
		{
			base.ProcessJsonRequest(context);

			if (context.Request["refreshProducts"] == "true")
			{
				string searchProduct = context.Request["searchProduct"];
				string productType = context.Request["productType"];

				System.Data.DataTable products = Page.Products;
				foreach (DataRow row in products.Rows)
				{
					string productName = row["DisplayName"].ToString();

					bool valid = true;
					if (!string.IsNullOrWhiteSpace(searchProduct))
					{
						try
						{
							valid = Regex.IsMatch(productName, searchProduct, RegexOptions.IgnoreCase);
							m_Regex = new Regex(searchProduct, RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
						}
						catch (Exception e)
						{
							m_Regex = null;
							valid = true;
						}
					}

					if (productType != "all")
					{
						string categoryId = row["ProductCategoryId"].ToString();
						switch (categoryId)
						{
							case "7":
								valid &= (productType == "mint");
								break;
							case "8":
								valid &= (productType == "neo");
								break;
							default:
								valid &= (productType == "others");
								break;
						}
					}

					if (!valid)
						continue;

					AddProductRow(row);
				}

				context.Json.Add("products", m_Table.ToString(RenderMode.Production, true, true));
				context.Json.Add("seqNo", context.Request["seqNo"]);
			}
		}

		public override void ProcessHtmlRequest(Jayden.Dll.Web.HttpHandlerContext context)
		{
			base.ProcessHtmlRequest(context);
			/*
			System.Data.DataTable products = Page.Products;
			foreach (DataRow row in products.Rows)
				AddProductRow(row);
			*/
		}

		protected void AddProductRow(DataRow row)
		{
			string productName = row["DisplayName"].ToString();

			string urlProductName = HttpUtility.UrlEncode(row["ProductName"].ToString());
			A localHost = new A("localhost");
			localHost.HRef = string.Format("http://localhost/net/{0}", urlProductName);

			A jvdw7 = new A("jvdw-7");
			jvdw7.HRef = string.Format("http://jvdw-7/net/{0}", urlProductName);

			A nettest2 = new A("nettest2");
			nettest2.HRef = string.Format("http://nettest2.be.bvdep.net/{0}", urlProductName);

			A setup = new A("setup");
			setup.HRef = row["WebRoot"].ToString();



			if (m_Table.ChildControls.Count == 0)
			{
				Th[] ths = m_Table.AddTHead().AddTr().AddTh
				(
					"Product",
					"Localhost",
					"JVDW-7",
					"Nettest2",
					"Setup"
				);
				ths[0].Style = "width:300px;";
				ths[1].Style = "width:75px;";
				ths[2].Style = "width:75px;";
				ths[3].Style = "width:75px;";
				ths[4].Style = "width:75px;";
			}

			Tr tr= m_Table.AddTr();
			Td[] tds = tr.AddTd
			(
				new HtmlText(productName),
				localHost,
				jvdw7,
				nettest2,
				setup
			);
			if (m_Regex != null)
				tr.MarkText(m_Regex, null);
		}
	}
}
